<template>
  <VPage>
    <VTable ref="tableRef" v-bind="tableOptins">
      <template #form="{ form }">
        <VGroup>
          <el-select v-model="form.dateRange.type" style="width: 100px">
            <el-option label="创建时间" value="create_time"></el-option>
            <el-option label="修改时间" value="update_time"></el-option>
          </el-select>
          <el-date-picker
            type="datetimerange"
            v-model="form.dateRange.value"
            clearable
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            style="min-width: 360px"
            value-format="YYYY-MM-DD HH:mm:ss"
            :default-time="defaultTime"
          />
        </VGroup>
      </template>
      <template #toolbar_btns>
        <el-button type="primary" @click="handleAdd" v-hasPermi="[departmentAuthList.list.add]"
          ><SvgIcon icon-class="Plus" class="text-[12px] mr-[6px]"/>新增</el-button
        >
      </template>
    </VTable>
    <Add
      v-model="addVisible"
      :data="addData"
      :options="departmentData"
      @refresh="refresh"
      @close="addData = {}"
    />
  </VPage>
</template>

<script setup name="List" lang="jsx">
import SvgIcon from "@/components/SvgIcon/index.vue";
import { department, detail, create, update, departmentDelete } from "./api";
import { ElMessage } from "element-plus";
const { proxy } = getCurrentInstance();
import Add from "./add/index";
import { defaultTime, treeToArray } from "./data.js";
import { departmentAuthList } from "@/Auth/department.js";
import { isPermission } from "@/hooks/permission.js";
const departmentData = ref([]);
const tableRef = ref();
const dialogPrompt = ref();
const ruleFormRef = ref();
const tableOptins = reactive({
  treeConfig: { transform: true, rowField: "id", parentField: "pid" },
  formConfig: {
    data: {
      dateRange: { type: "create_time", value: [], range: true }, // 组合+日期范围
    },
  },
  columns: [
    {
      field: "name",
      title: "部门名称",
      treeNode: "tree-node",
      minWidth: "200",
    },
    { field: "create_time", title: "创建时间", width: "200" },
    { field: "update_user_text", title: "修改人", width: "200" },
    { field: "update_time", title: "修改时间", width: "200" },
    {
      title: "操作",
      fixed: "right",
      width: "180",
      slots: {
        default: ({ row }) => {
          return (
            <div>
              {isPermission([departmentAuthList.list.add_department]) && (
                <el-button
                  type="primary"
                  link
                  onClick={() => {
                    handleAdd(null, row);
                  }}
                >
                  新增部门
                </el-button>
              )}
              {isPermission([departmentAuthList.list.edit]) && (
                <el-button
                  type="primary"
                  onClick={() => {
                    handleAdd(row);
                  }}
                  link
                >
                  编辑
                </el-button>
              )}
              {isPermission([departmentAuthList.list.delete]) && (
                <el-button
                  type="danger"
                  onClick={() => {
                    handleDelete(row.id);
                  }}
                  link
                >
                  删除
                </el-button>
              )}
            </div>
          );
        },
      },
    },
  ],
  proxyConfig: {
    ajax: {
      query: async ({ page, form }) => {
        return department({ ...form, ...page }).then((res) => {
          departmentData.value = res.data;
          let data = treeToArray(res.data);
          return {
            data: data,
            total: data.length,
          };
        });
      },
    },
  },
});
//更新表格数据
const refresh = () => {
  tableRef?.value.$table.commitProxy("query");
};
//表单校验验证

//添加部门或者编辑
const addData = ref({});
const addVisible = ref(false);
const handleAdd = (id = null, row = null) => {
  const { id: newId, pid: newPid } = id || {};
  addData.value = {
    id: newId || null,
    pid: newId ? newPid : row?.id || null,
  };
  addVisible.value = true;
};

const handleDelete = (id) => {
  proxy?.confirm({
    title: "提示",
    content: (
      <p>
        确认删除
        <span class="text-[#3366F1] px-[4px]">{1}</span>
        条数据？
      </p>
    ),
    beforeClose: async (action, instance, done) => {
      if (action === "confirm") {
        try {
          instance.confirmButtonLoading = true;
          instance.confirmButtonText = "处理中..";
          const { code, message } = await departmentDelete({ id });
          if (code !== 200) return ElMessage.success(message);
          ElMessage.success("删除成功!");
        } catch (e) {
          console.error(e);
        } finally {
          instance.confirmButtonLoading = false;
          done();
          refresh();
        }
      } else {
        done();
      }
    },
  });
};
</script>
<style scoped lang="scss">
.vxy-table {
  width: 100%;
  height: calc(100% - 65px);
}
:deep(.vxe-grid--pager-wrapper) {
  display: none;
}
</style>
